package net.kelissa.jenetic;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class RandomUtil
{

  protected static Random random;

  public static Random getRandom()
  {
    if (random == null)
      random = new Random();
    return random;
  }

  public static <E> E getX2Random(List<E> list)
  {
    double rand = getRandom().nextDouble();
    rand = rand * rand;
    rand = rand * list.size();
    return list.get((int) rand);
  }

  public static <E> E getRandom(List<E> list)
  {
    double rand = getRandom().nextDouble() * list.size();
    return list.get((int) rand);
  }

  public static <E> void permutation(List<E> list)
  {
    int rand = RandomUtil.getRandom().nextInt(list.size());
    E removed = list.remove(rand);
    rand = RandomUtil.getRandom().nextInt(list.size());
    list.add(rand, removed);
  }


  public static double getRandomDouble()
  {
    return getRandom().nextDouble();
  }

  public static double getRandom(double randMin, double randMax)
  {
    double rand = getRandom().nextDouble();
    rand = (rand * (randMax - randMin)) + randMin;
    return rand;
  }

  /**
   *
   * @param randMin
   * @param randMax
   * @return random integer from randMin included and randMax excluded
   */
  public static int getRandom(int randMin, int randMax)
  {
    int rand = getRandom().nextInt(randMax - randMin);
    rand += randMin;
    return rand;
  }

  public static <E> void shuffle(List<E> list)
  {
    for (int i = 0; i < list.size(); i++)
    {
      int rand2 = RandomUtil.getRandom().nextInt(list.size());
      E value1 = list.get(i);
      E value2 = list.get(rand2);
      list.remove(i);
      list.add(i, value2);
      list.remove(rand2);
      list.add(rand2, value1);
    }
  }

  public static List<Gene> clone(List<Gene> genes)
  {
    //TODO non va qui, o no?
    List<Gene> clone = new ArrayList<Gene>();
    for (Gene gene : genes)
    {
      clone.add(gene.clone());
    }
    return clone;
  }

}
